<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="进食名称" prop="eatName">
        <el-input
          v-model="queryParams.eatName"
          placeholder="请输入进食名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="餐次" prop="timeInterval">
        <el-select
          v-model="queryParams.timeInterval"
          placeholder="请选择餐次"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="dict in meal_time"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="进食日期" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择进食日期"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          :type="buttonName == '新增' ? 'primary' : 'success'"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:eat:add']"
        >
          {{ buttonName }}
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          @click="handleUpdate"
          v-hasPermi="['manage:eat:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:eat:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:eat:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="eatList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" width="50" />
      <el-table-column label="食物名称" align="center" prop="eatName" />
      <el-table-column
        label="食物图片"
        align="center"
        prop="imgUrl"
        width="100"
      >
        <template #default="scope">
          <image-preview :src="scope.row.imgUrl" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="进食量" align="center" prop="amount">
        <template #default="scope">
          <span>{{ scope.row.amount }}克</span>
        </template>
      </el-table-column>
      <el-table-column label="餐次" align="center" prop="timeInterval">
        <template #default="scope">
          <dict-tag :options="meal_time" :value="scope.row.timeInterval" />
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        show-overflow-tooltip
      />
      <el-table-column
        label="录入时间"
        align="center"
        prop="createTime"
        width="180"
        sortable
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:eat:edit']">修改</el-button> -->
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:eat:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改进食记录对话框 -->
    <el-dialog :title="title" v-model="open" width="810" append-to-body>
      <el-form ref="eatRef" :model="form" :rules="rules" label-width="80px">
        <el-tabs
          :tab-position="tabPosition"
          v-model="activeTab"
          @tab-click="handleTabClick"
        >
          <el-tab-pane label="早餐" name="breakfast">
            <template #default>
              <el-table
                :data="form.breakfastList"
                style="width: 100%"
                :resizable="false"
              >
                <el-table-column
                  label="食物名称"
                  align="center"
                  prop="eatName"
                  width="160"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.eatName"
                      placeholder="请输入食物名称"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="食物图片"
                  prop="imgUrl"
                  align="center"
                  width="80"
                >
                  <template #default="scope">
                    <el-upload
                      class="avatar-uploader"
                      :action="uploadFileUrl"
                      :show-file-list="false"
                      :headers="headers"
                      :on-error="handleUploadError"
                      :on-success="
                        (response, file) =>
                          handleUploadSuccess(
                            response,
                            file,
                            scope.$index,
                            'breakfast'
                          )
                      "
                      :before-upload="handleBeforeUpload"
                      :limit="1"
                      :on-remove="
                        (file, fileList) =>
                          handleRemove(file, fileList, scope.$index)
                      "
                    >
                      <el-image
                        v-if="scope.row.imgUrl"
                        :src="scope.row.imgUrl"
                        class="avatar"
                        @click.stop="handlePictureCardPreview(scope.row.imgUrl)"
                      />
                      <el-icon v-else class="avatar-uploader-icon"
                        ><Plus
                      /></el-icon>
                    </el-upload>
                  </template>
                </el-table-column>
                <el-table-column
                  label="进食量"
                  prop="amount"
                  align="center"
                  width="200"
                >
                  <template #default="scope">
                    <el-input-number
                      v-model="scope.row.amount"
                      :min="0.1"
                      style="width: 70%"
                      :precision="1"
                      :step="0.1"
                    />
                    <span style="margin-left: 10px">克</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="备注"
                  prop="remark"
                  align="center"
                  width="150"
                >
                  <template #default="scope">
                    <el-popover
                      placement="top-end"
                      :width="400"
                      trigger="manual"
                      :visible="scope.row.popoverVisible"
                    >
                      <el-input
                        type="textarea"
                        :rows="4"
                        placeholder="请输入内容"
                        v-model="scope.row.remark"
                      />
                      <div style="text-align: right; margin-top: 8px">
                        <el-button size="small" @click="closePopover(scope.row)"
                          >取 消</el-button
                        >
                        <el-button
                          type="primary"
                          size="small"
                          @click="confirmEdit(scope.row)"
                          >确 定</el-button
                        >
                      </div>
                      <template #reference>
                        <el-input
                          v-model="scope.row.remark"
                          placeholder="请输入备注"
                          @click="openPopover(scope.row)"
                        >
                        </el-input>
                      </template>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" align="center">
                  <template #default="scope">
                    <el-button
                      link
                      type="danger"
                      icon="Delete"
                      @click="handleRemoveItem(scope.$index, 'breakfast')"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <!-- 按钮居中 -->
              <div
                style="display: flex; justify-content: center; margin-top: 10px"
              >
                <el-button
                  plain
                  link
                  icon="CirclePlus"
                  type="primary"
                  @click="handleAddItem('breakfast')"
                  >新增</el-button
                >
              </div>
            </template>
          </el-tab-pane>
          <el-tab-pane label="午餐" name="lunch">
            <template #default>
              <el-table
                :data="form.lunchList"
                style="width: 100%"
                :resizable="false"
              >
                <el-table-column
                  label="食物名称"
                  prop="eatName"
                  align="center"
                  width="160"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.eatName"
                      placeholder="请输入食物名称"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="食物图片"
                  prop="imgUrl"
                  align="center"
                  width="80"
                >
                  <template #default="scope">
                    <el-upload
                      class="avatar-uploader"
                      :action="uploadFileUrl"
                      :show-file-list="false"
                      :headers="headers"
                      :on-error="handleUploadError"
                      :on-success="
                        (response, file) =>
                          handleUploadSuccess(
                            response,
                            file,
                            scope.$index,
                            'lunch'
                          )
                      "
                      :before-upload="handleBeforeUpload"
                      :limit="1"
                      :on-remove="
                        (file, fileList) =>
                          handleRemove(file, fileList, scope.$index)
                      "
                    >
                      <el-image
                        v-if="scope.row.imgUrl"
                        :src="scope.row.imgUrl"
                        class="avatar"
                        @click.stop="handlePictureCardPreview(scope.row.imgUrl)"
                      />
                      <el-icon v-else class="avatar-uploader-icon"
                        ><Plus
                      /></el-icon>
                    </el-upload>
                  </template>
                </el-table-column>
                <el-table-column
                  label="进食量"
                  prop="amount"
                  align="center"
                  width="200"
                >
                  <template #default="scope">
                    <el-input-number
                      v-model="scope.row.amount"
                      :min="0.1"
                      style="width: 70%"
                      :precision="1"
                      :step="0.1"
                    />
                    <span style="margin-left: 10px">克</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="备注"
                  prop="remark"
                  align="center"
                  width="150"
                >
                  <template #default="scope">
                    <el-popover
                      placement="top-end"
                      :width="400"
                      trigger="manual"
                      :visible="scope.row.popoverVisible"
                    >
                      <el-input
                        type="textarea"
                        :rows="4"
                        placeholder="请输入内容"
                        v-model="scope.row.remark"
                      />
                      <div style="text-align: right; margin-top: 8px">
                        <el-button size="small" @click="closePopover(scope.row)"
                          >取 消</el-button
                        >
                        <el-button
                          type="primary"
                          size="small"
                          @click="confirmEdit(scope.row)"
                          >确 定</el-button
                        >
                      </div>
                      <template #reference>
                        <el-input
                          v-model="scope.row.remark"
                          placeholder="请输入备注"
                          @click="openPopover(scope.row)"
                        >
                        </el-input>
                      </template>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" align="center">
                  <template #default="scope">
                    <el-button
                      link
                      type="danger"
                      icon="Delete"
                      @click="handleRemoveItem(scope.$index, 'lunch')"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <!-- 按钮居中 -->
              <div
                style="display: flex; justify-content: center; margin-top: 10px"
              >
                <el-button
                  plain
                  link
                  icon="CirclePlus"
                  type="primary"
                  @click="handleAddItem('lunch')"
                  >新增</el-button
                >
              </div>
            </template>
          </el-tab-pane>
          <el-tab-pane label="晚餐" name="dinner">
            <template #default>
              <el-table
                :data="form.dinnerList"
                style="width: 100%"
                :resizable="false"
              >
                <el-table-column
                  label="食物名称"
                  prop="eatName"
                  align="center"
                  width="160"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.eatName"
                      placeholder="请输入食物名称"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="食物图片"
                  prop="imgUrl"
                  align="center"
                  width="80"
                >
                  <template #default="scope">
                    <el-upload
                      class="avatar-uploader"
                      :action="uploadFileUrl"
                      :show-file-list="false"
                      :headers="headers"
                      :on-error="handleUploadError"
                      :on-success="
                        (response, file) =>
                          handleUploadSuccess(
                            response,
                            file,
                            scope.$index,
                            'dinner'
                          )
                      "
                      :before-upload="handleBeforeUpload"
                      :limit="1"
                      :on-remove="
                        (file, fileList) =>
                          handleRemove(file, fileList, scope.$index)
                      "
                    >
                      <el-image
                        v-if="scope.row.imgUrl"
                        :src="scope.row.imgUrl"
                        class="avatar"
                        @click.stop="handlePictureCardPreview(scope.row.imgUrl)"
                      />
                      <el-icon v-else class="avatar-uploader-icon"
                        ><Plus
                      /></el-icon>
                    </el-upload>
                  </template>
                </el-table-column>
                <el-table-column
                  label="进食量"
                  prop="amount"
                  align="center"
                  width="200"
                >
                  <template #default="scope">
                    <el-input-number
                      v-model="scope.row.amount"
                      :min="0.1"
                      style="width: 70%"
                      :precision="1"
                      :step="0.1"
                    />
                    <span style="margin-left: 10px">克</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="备注"
                  prop="remark"
                  align="center"
                  width="150"
                >
                  <template #default="scope">
                    <el-popover
                      placement="top-end"
                      :width="400"
                      trigger="manual"
                      :visible="scope.row.popoverVisible"
                    >
                      <el-input
                        type="textarea"
                        :rows="4"
                        placeholder="请输入内容"
                        v-model="scope.row.remark"
                      />
                      <div style="text-align: right; margin-top: 8px">
                        <el-button size="small" @click="closePopover(scope.row)"
                          >取 消</el-button
                        >
                        <el-button
                          type="primary"
                          size="small"
                          @click="confirmEdit(scope.row)"
                          >确 定</el-button
                        >
                      </div>
                      <template #reference>
                        <el-input
                          v-model="scope.row.remark"
                          placeholder="请输入备注"
                          @click="openPopover(scope.row)"
                        >
                        </el-input>
                      </template>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" align="center">
                  <template #default="scope">
                    <el-button
                      link
                      type="danger"
                      icon="Delete"
                      @click="handleRemoveItem(scope.$index, 'dinner')"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <!-- 按钮居中 -->
              <div
                style="display: flex; justify-content: center; margin-top: 10px"
              >
                <el-button
                  plain
                  icon="CirclePlus"
                  link
                  type="primary"
                  @click="handleAddItem('dinner')"
                  >新增</el-button
                >
              </div>
            </template>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog
      v-model="dialogVisible"
      title="预览"
      width="800px"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>

<script setup name="Eat">
import { listEat, getEat, delEat, addEat, updateEat } from "@/api/manage/eat"
import { getToken } from "@/utils/auth"
import { ref } from "vue"


const { proxy } = getCurrentInstance()
const { meal_time } = proxy.useDict('meal_time')

const dialogImageUrl = ref("")
const dialogVisible = ref(false)
const eatList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("添加进食记录")
const buttonName = ref("新增")
const breakfastList = ref([])
const lunchList = ref([])
const dinnerList = ref([])

const tabPosition = ref('left')

const activeTab = ref("breakfast")

const data = reactive({
  form: {
    breakfastList: [],
    lunchList: [],
    dinnerList: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    eatName: null,
    timeInterval: null,
    remark: null,
    createTime: null
  },
  rules: {
    eatName: [
      { required: true, message: "食物名称不能为空", trigger: "blur" }
    ],
    amount: [
      { required: true, message: "进食量不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// 监听 form 中的三个列表的变化
watch(() => [breakfastList.value.length, lunchList.value.length, dinnerList.value.length], ([breakfastLength, lunchLength, dinnerLength]) => {
  if (breakfastLength > 0 || lunchLength > 0 || dinnerLength > 0) {
    buttonName.value = "修改"
    title.value = "修改进食记录"
  } else {
    buttonName.value = "新增"
    title.value = "新增进食记录"
  }
}, { immediate: true })

/** 查询进食记录列表 */
function getList () {
  loading.value = true
  listEat(queryParams.value).then(response => {
    eatList.value = response.rows
    total.value = response.total
    loading.value = false
  })
  getFormEatList()
}

function getFormEatList () {
  const now = new Date()
  const data = {}
  data.createTime = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate()
  listEat(data).then(response => {
    // 提取出response.rows中所有timeInterval为0，1，2的数据
    breakfastList.value = response.rows.filter(item => item.timeInterval === 0)
    lunchList.value = response.rows.filter(item => item.timeInterval === 1)
    dinnerList.value = response.rows.filter(item => item.timeInterval === 2)
  })
}

// 取消按钮
function cancel () {
  open.value = false
  reset()
}

// 表单重置
function reset () {
  form.value = {
    eatId: null,
    eatName: null,
    imgUrl: null,
    amount: null,
    timeInterval: null,
    remark: null,
    createTime: null,
    // breakfastList: [],
    // lunchList: [],
    // dinnerList: []
  }
  proxy.resetForm("eatRef")
}

/** 搜索按钮操作 */
function handleQuery () {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery () {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange (selection) {
  ids.value = selection.map(item => item.eatId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd () {
  reset()
  getFormEatList()
  form.value.breakfastList = [...breakfastList.value]
  form.value.lunchList = [...lunchList.value]
  form.value.dinnerList = [...dinnerList.value]
  console.log("formValue", form.value)
  open.value = true
  // title.value = "添加进食记录";
}

/** 修改按钮操作 */
function handleUpdate (row) {
  reset()
  // const _eatId = row.eatId || ids.value
  // getEat(_eatId).then(response => {
  //   form.value = response.data;
  //   open.value = true;
  //   title.value = "修改进食记录";
  // });
  // 获取当前时间，格式为yyyy-MM-dd
  // const now = new Date();
  // const data = {};
  // data.createTime = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
  // listEat(data).then(response => {
  //   // 提取出response.rows中所有timeInterval为0，1，2的数据
  //   const breakfastList = response.rows.filter(item => item.timeInterval === 0);
  //   const lunchList = response.rows.filter(item => item.timeInterval === 1);
  //   const dinnerList = response.rows.filter(item => item.timeInterval === 2);
  //   form.value.breakfastList = breakfastList;
  //   form.value.lunchList = lunchList;
  //   form.value.dinnerList = dinnerList;
  //   open.value = true;
  //   title.value = "修改进食记录";
  // });
}

// 检查每个List中是否有重复的eatName
const hasDuplicateNames = (list) => {
  const names = list.map(eat => eat.eatName)
  return new Set(names).size !== names.length
}

/** 提交按钮 */
function submitForm () {
  // 检查每个餐点的数据是否有效
  const hasEmptyItem = (list) => {
    return list.some(item => !item.eatName || !item.amount)
  }
  
  if (hasEmptyItem(form.value.breakfastList) || 
      hasEmptyItem(form.value.lunchList) || 
      hasEmptyItem(form.value.dinnerList)) {
    proxy.$modal.msgError('请填写完整的食物名称和进食量')
    return
  }

  // 检查是否有至少一个餐点有数据
  if (form.value.breakfastList.length === 0 && 
      form.value.lunchList.length === 0 && 
      form.value.dinnerList.length === 0) {
    proxy.$modal.msgError('至少需要添加一种餐点的进食记录')
    return
  }
  form.value.breakfastList.map(eat => {
    // 给每个元素添加time_interval
    eat.timeInterval = 0
  })
  form.value.lunchList.map(eat => {
    // 给每个元素添加time_interval
    eat.timeInterval = 1
  })
  form.value.dinnerList.map(eat => {
    // 给每个元素添加time_interval
    eat.timeInterval = 2
  })
  if (hasDuplicateNames(form.value.breakfastList)) {
    proxy.$modal.msgError("早餐列表中存在重复的名称")
    return
  }
  if (hasDuplicateNames(form.value.lunchList)) {
    proxy.$modal.msgError("午餐列表中存在重复的名称")
    return
  }
  if (hasDuplicateNames(form.value.dinnerList)) {
    proxy.$modal.msgError("晚餐列表中存在重复的名称")
    return
  }
  // 将三个数组合并成一个数组
  const eatList = form.value.breakfastList.concat(form.value.lunchList, form.value.dinnerList)
  console.log("eatList", eatList)
  // 检查eatList中的每个元素的eat_id是否为空
  const isUpdate = eatList.some(eat => eat.eatId !== null && eat.eatId !== undefined)
  proxy.$refs["eatRef"].validate(valid => {
    if (valid) {
      if (isUpdate) {
        updateEat(eatList).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addEat(eatList).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete (row) {
  const _eatIds = row.eatId || ids.value
  const delName = _eatIds.length >= 1 ? '选中的清单' : row.eatName
  proxy.$modal.confirm('确定要删除' + delName + '吗？').then(function () {
    return delEat(_eatIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport () {
  proxy.download('manage/eat/export', {
    ...queryParams.value
  }, `eat_${new Date().getTime()}.xlsx`)
}

// 新增进食记录
function handleAddItem (mealType) {
  if (mealType === 'breakfast') {
    form.value.breakfastList.push({})
  } else if (mealType === 'lunch') {
    form.value.lunchList.push({})
  } else {
    form.value.dinnerList.push({})
  }
}

// 删除进食记录
function handleRemoveItem (index, mealType) {
  if (mealType === 'breakfast') {
    form.value.breakfastList.splice(index, 1)
  } else if (mealType === 'lunch') {
    form.value.lunchList.splice(index, 1)
  } else {
    form.value.dinnerList.splice(index, 1)
  }
}

/** 上传地址 **/
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload")
/** 上传请求头 **/
const headers = ref({ "Authorization": "Bearer " + getToken() })

// 上传失败
function handleUploadError () {
  proxy.$modal.msgError("上传图片失败")
  proxy.$modal.closeLoading()
}

/** 上传前校验 **/
const props = defineProps({
  modelValue: [String, Object, Array],
  // 图片数量限制
  limit: {
    type: Number,
    default: 1,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["png", "jpg", "jpeg"],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: false
  },
})

// 上传前loading加载
function handleBeforeUpload (file) {
  console.log("测试file", file)
  let isImg = false
  if (props.fileType.length) {
    let fileExtension = ""
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1)
    }
    isImg = props.fileType.some(type => {
      if (file.type.indexOf(type) > -1) return true
      if (fileExtension && fileExtension.indexOf(type) > -1) return true
      return false
    })
  } else {
    isImg = file.type.indexOf("image") > -1
  }
  if (!isImg) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join("/")}图片格式文件!`
    )
    return false
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize
    if (!isLt) {
      proxy.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`)
      return false
    }
  }
  proxy.$modal.loading("正在上传图片，请稍候...")
  return true
}

// 上传成功回调
function handleUploadSuccess (res, file, index, mealType) {
  console.log("handleUploadSuccess", res, file)
  if (res.code === 200) {
    // 获取服务器返回的图片URL
    const imageUrl = res.url // 从res对象中获取图片URL
    if (mealType === 'breakfast') {
      form.value.breakfastList[index].imgUrl = imageUrl
    } else if (mealType === 'lunch') {
      form.value.lunchList[index].imgUrl = imageUrl
    } else {
      form.value.dinnerList[index].imgUrl = imageUrl
    }
  } else {
    proxy.$modal.msgError("图片上传失败")
  }
  proxy.$modal.closeLoading()
}

// 删除图片的函数
const handleRemove = async (file, fileList, index) => {
  const row1 = form.value.breakfastList[index]
  const row2 = form.value.lunchList[index]
  const row3 = form.value.dinnerList[index]
  // 清除本地状态
  row1.imgUrl = '' // 清除图片链接
  row2.imgUrl = '' // 清除图片链接
  row3.imgUrl = '' // 清除图片链接
}

// 预览
function handlePictureCardPreview (url) {
  dialogImageUrl.value = url
  dialogVisible.value = true
}

function openPopover (row) {
  if (!row.popoverVisible) {  // 防止重复打开
    row.popoverVisible = true
    // 保存当前备注内容作为原始值
    row.originalRemark = row.remark
  }
};

function confirmEdit (row) {
  row.popoverVisible = false
  // 确认编辑后，更新原始值
  row.originalRemark = row.remark
};

// 关闭 Popover
function closePopover (row) {
  row.popoverVisible = false
  // 恢复为原始值而不是清空
  row.remark = row.originalRemark
};


function handleTabClick () {
  let listName = activeTab.value
  let list = []
  // console.log("listName", listName)
  if (listName === 'breakfast') {
    list = form.value.breakfastList
  } else if (listName === 'lunch') {
    list = form.value.lunchList
  } else {
    list = form.value.dinnerList
  }
  // console.log("list", list)
  if (list !== null) {
    list.forEach(row => {
      row.popoverVisible = false
    })
  }
}

getList()
getFormEatList();
</script>

<style scope>
.avatar-uploader .avatar {
  width: 40px;
  height: 40px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 40px;
  height: 40px;
  text-align: center;
}
</style>